package com.Controller;
import com.dao.*;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import com.service.*;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.descriptor.web.LoginConfig;

import com.moddel.*;
//import jdk.internal.dynalink.beans.StaticClass;

public class newsSerclet extends HttpServlet {

	
	public newsSerclet() {
		super();
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	
	public  void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           
		 request.setCharacterEncoding("utf-8");
         response.setCharacterEncoding("utf-8");
		 String flag=request.getParameter("flag");
         switch(flag){
             case "addNews":{
            	 //System.out.println(flag);
            	insertNews(request,response);
            	 break;
             }
             case "mangerNews":{
            	 try {
            		 //System.out.println(flag);
					selectAllNews(request, response);
				} catch (SQLException | NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	 break;
             }
             case "delete":{
            	 deleteNews(request, response);
            	 break;
             }
             case "update":{
            	 try {
					updateNews(request, response);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	 break;
             }
             case "login":{
            	 login(request, response);
            	 break;
             }
             case "selectImage":{
            	 selectImage(request, response);
            	 break;
             }
             case "setInforToUser":{
            	 try {
            		 setInforToUser(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	 break;
             }
             case "newsdetail":{
            	 selectNewsDetail(request, response);
            	 break;
             }
             case "userBm":{
            	 userBm(request,response);
            	 break;
             }
             case "getbmb":{
            	 getBmb(request,response);
            	 break;
             }
             

          }    
		
    }
	private static void insertNews(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		 String title=request.getParameter("title");
	   	 String type=request.getParameter("type");
	   	 String maker=request.getParameter("maker");
	   	 String date=request.getParameter("date");
	   	 String content=request.getParameter("content");
	   	 int tid=Integer.parseInt(request.getParameter("tid"));
	   	 String image1=request.getParameter("img1");
	   	 String image2=request.getParameter("img2");
	   	 String image3=request.getParameter("img3");
	     String image4=request.getParameter("img4");
	   	 NewsDao addNews=new NewsDao();
	   	 boolean ifInsert1=false;
	   	 boolean ifInsert2=false;
	   	 ifInsert1=addNews.insertNews(tid,title, type, maker, date, content);
	   	 ifInsert2=addNews.insertImage(tid, image1, image2, image3, image4);
	   	 if(ifInsert1==true&&ifInsert2==true){
   		 request.getRequestDispatcher("reminder.jsp?infor=添加成功!!!").forward(request, response);
	   	 }else{
	   		 request.getRequestDispatcher("reminder.jsp?infor=添加失败!!!").forward(request, response);
	   	 }
	}
	private static void selectAllNews(HttpServletRequest request, HttpServletResponse response) throws SQLException, NamingException{
		int pageSize=Integer.parseInt(request.getParameter("pagesize"));
		int pageNow=Integer.parseInt(request.getParameter("pagenow"));
		SelectNewsService mangerNews=new SelectNewsService();
		int rowCount=mangerNews.getRowCount();
		int pageCount=mangerNews.getPageCount(pageSize);
		ArrayList<news> newsList=mangerNews.SelectNews(pageNow,pageSize);
		request.setAttribute("newsList", newsList);
		System.out.println("dasfa=="+pageSize);
		try {
			if(pageSize==17){
			    request.getRequestDispatcher("mangerNews.jsp?pageCount="+pageCount+ "&pageNow="+pageNow+"&rowCount="+rowCount).forward(request, response);
			}else{
				request.getRequestDispatcher("userPlatform.jsp?pageCount="+pageCount+ "&pageNow="+pageNow+"&rowCount="+rowCount).forward(request, response);
			}
			} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	}
	
	private static void deleteNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		boolean ifDel=false;
		int id=Integer.parseInt(request.getParameter("id"));
		NewsDao delNews=new NewsDao();
		ifDel=delNews.deleteNews(id);
		if(ifDel!=false){
			 request.getRequestDispatcher("reminder.jsp?infor=删除成功!!!").forward(request, response);
		}else{
			 request.getRequestDispatcher("reminder.jsp?infor=删除失败!!!").forward(request, response);
		}
	}
	private static void updateNews(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException{
		int id=Integer.parseInt(request.getParameter("id"));
		String title=request.getParameter("title");
		String type=request.getParameter("type");
		String maker=request.getParameter("maker");
		String date=request.getParameter("date");
		boolean ifUpdate=false;
		NewsDao updateNews=new NewsDao();
		ifUpdate=updateNews.UpdateNews(id, title, type, date, maker);
		if(ifUpdate!=false){
			request.getRequestDispatcher("reminder.jsp?infor=修改成功！！！").forward(request, response);
		}else{
			request.getRequestDispatcher("reminder.jsp?infor=修改失败！！！").forward(request, response);	
		}
		
	}
	private static void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String username=request.getParameter("username");
		String passwd=request.getParameter("passwd");
		SelectNewsService login=new SelectNewsService();
		boolean ifLogin=login.ifLogin(username, passwd);
		if(ifLogin!=false){
			   request.getRequestDispatcher("main.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("login.jsp?infor=用户名或密码错误请重新登录").forward(request, response);	
		}
		
	}
	
	private static void selectImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		imageDao img=new imageDao();
		ArrayList<ImageB> list=new ArrayList<ImageB>();
		list=img.selectImage();
		//System.out.println("sadgsdg==="+list);
		request.setAttribute("list", list);
		request.getRequestDispatcher("addNews.jsp").forward(request, response);
	}
	private static ArrayList<news> selectAllNewsToUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, NamingException{
		int pageSize=Integer.parseInt(request.getParameter("pagesizeNews"));
		int pageNow=Integer.parseInt(request.getParameter("pagenowNews"));
		SelectNewsService mangerNews=new SelectNewsService();
		int rowCount=mangerNews.getRowCount();
		int pageCount=mangerNews.getPageCount(pageSize);
		ArrayList<news> newsList=mangerNews.SelectNews(pageNow,pageSize);
		return newsList;
		
	}
	private static ArrayList<makeB> selectMake(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		int pageSize=Integer.parseInt(request.getParameter("pagesizeM"));
		int pageNow=Integer.parseInt(request.getParameter("pagenowM"));
		imageDao sm=new imageDao();
		ArrayList<makeB> list_2=new ArrayList<makeB>();
		list_2=sm.selectAllMake(pageSize,pageNow);
		return list_2;
	}
	public static ArrayList<ImageB> selectPhotoNews(HttpServletRequest request, HttpServletResponse response){
		int id=Integer.parseInt(request.getParameter("id"));
		ArrayList<ImageB> list=new ArrayList<ImageB>();
		imageDao pn=new imageDao();
		list=pn.selectPhotoNews(id);
		return list;
	}
	private static void setInforToUser(HttpServletRequest request, HttpServletResponse response){	
		String username=request.getParameter("username");
		String passwd=request.getParameter("passwd");
		SelectNewsService login=new SelectNewsService();
		boolean ifLogin=login.ifLogin(username, passwd);
		int pageSize=Integer.parseInt(request.getParameter("pagesizeNews"));
		int pageNow=Integer.parseInt(request.getParameter("pagenowNews"));
		SelectNewsService mangerNews=new SelectNewsService();
		try {
			int rowCount=mangerNews.getRowCount();
			int pageCount=mangerNews.getPageCount(pageSize);
			ArrayList<news> userListNew=selectAllNewsToUser( request,response);
			ArrayList<makeB> userListMake=selectMake(request, response);
			ArrayList<ImageB> pnList=selectPhotoNews(request, response);
			request.setAttribute("userListNew", userListNew);
			request.setAttribute("userListMake", userListMake);
			request.setAttribute("pnList", pnList);
			if(ifLogin==true){
			    request.getRequestDispatcher("userPlatform.jsp?pageCount="+pageCount+ "&pageNow="+pageNow+"&rowCount="+rowCount).forward(request, response);
			}else {
				request.getRequestDispatcher("userLogin.jsp?infor=用户名或密码错误请重新登录").forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	private static void selectNewsDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		int id=Integer.parseInt(request.getParameter("id"));
		NewsDao snd=new NewsDao();
		ArrayList<news> listsnd=snd.selectNewsDetail(id);
		request.setAttribute("listsnd", listsnd);
		request.getRequestDispatcher("newsDetail.jsp").forward(request, response);
	}
	
	private static void userBm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		DiskFileItemFactory factory=new DiskFileItemFactory();
		String path=request.getRealPath("/upload");
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024*1024);
		ServletFileUpload upload=new ServletFileUpload(factory);
		boolean ifinsert=false;
		userBm ubm=new userBm();
		try{
			java.util.List<FileItem> list=(java.util.List<FileItem>)upload.parseRequest(request);//对requests对象进行解析,并把表单中的每一个输入项包装成一个fileItem对象,并返回一个保存了所有FileItem的list集合.
			for(FileItem item:list){
				if(item.isFormField()){
					String name=item.getFieldName();
					String value=item.getString();
					value = new String(value.getBytes("ISO8859_1"), "utf-8");//乱码处理 
					request.setAttribute("value", value);
					switch(name){
					    case "name":ubm.setName(value);break;
					    case "nianji":ubm.setNianji(value);break;
					    case "xueyuan":ubm.setXueyuan(value);break;
					    case "want":ubm.setWant(value);break;
					    case "email":ubm.setEmail(value);break;
					    case "major":ubm.setMajor(value);break;
					    case "photoNumber":ubm.setPhotoNumber(value);break;
					    case "max":ubm.setMax(value);break;
					    case "pjia":ubm.setPjia(value);break;
					    case "aboutMy":ubm.setAboutmy(value);
					}
				}else{
					String value=item.getName();
					int start=value.lastIndexOf("\\");
					String fileName=value.substring(start+1);//防止不同浏览器返回的文件名不同
					ubm.setPhoto(fileName);
				    request.setAttribute("fileName", fileName);
				    item.write(new File(path,fileName));//将上传的文件写到path路径下，文件名为filename
				}
		    }
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		SelectNewsService insertUserInfor=new SelectNewsService();
		System.out.println("photoNumber=="+ubm.getPhotoNumber());
		ifinsert=insertUserInfor.insertUserInfor(ubm);
		if(ifinsert==true)
			request.getRequestDispatcher("reminder.jsp?infor=报名成功！！！").forward(request, response);
		else {
			request.getRequestDispatcher("reminder.jsp?infor=报名失败！！！").forward(request, response);
		}
		
   }
	private static void getBmb(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		int id=Integer.parseInt(request.getParameter("id"));
		NewsDao nDao=new NewsDao();
		ArrayList<userBm> list=nDao.getUserInfor(id);
		request.setAttribute("list", list);
		request.getRequestDispatcher("bmb.jsp?id="+id).forward(request, response);
	} 
	
}
